package com.zhao.dota.config;

import com.zhao.dota.exception.FlowException;
import com.zhao.dota.struct.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Resource
    private AccessDeniedHandler accessDeniedHandler;
    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;

    @ExceptionHandler(AccessDeniedException.class)
    public void handleAccessDeniedException(AccessDeniedException e) throws IOException, ServletException {
        accessDeniedHandler.handle(request, response, e);
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> error(Exception e) {
        String message = e == null ? null : e.getMessage();
        if (!(e instanceof FlowException)) {
            log.error("GlobalExceptionHandler：" + message, e);
        }
        return Result.error(message);
    }

}
